package br.com.post.persistence;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.post.model.User;

public class UserDao {
	private static UserDao instance;
	/**
	 * Persiste usuario no banco
	 * @param user
	 */
	public void createUser(User user) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();
	}
	
	/**
	 * Atualiza o usuario no banco
	 * @param user
	 */
	public void updateUser(User user) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.merge(user);
		tx.commit();
		session.close();
	}
	
	/**
	 * Seleciona um usuario no banco de acordo com o id(long)
	 * @param user_id
	 * @return user
	 */
	public User selectUser(long user_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		User user = (User)session.get(User.class,user_id);
		tx.commit();
		session.close();
		return user;
	}
	
	/**
	 * Deleta o usuario de acordo com o id, primeiro faz um select
	 * para o hibernate entender, depois remove o usuario selecionado
	 * @param user_id
	 */
	public void deleteUser(long user_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		User user=selectUser(user_id);
		session.delete(user);
		tx.commit();
		session.close();
	}

	public static UserDao getInstance() {
		if(instance == null)
			instance = new UserDao();
		return instance;
	}

	public static void setInstance(UserDao instance) {
		UserDao.instance = instance;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getList(){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		List<User> userlist = (List<User>) session.createQuery("from User u order by u.user_name").list();
		tx.commit();
		session.close();
		return userlist;
	}

	public User selectUserByLoginPass(String login, String password) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Query q = session.createQuery("select u from User u where u.user_nick=? and u.user_password=?");
		q.setParameter(0,login);
		q.setParameter(1, password);
		User user= (User) q.uniqueResult();
		tx.commit();
		session.close();
		return user;
	}

	public User selectUserByEmail(String user_email) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Query q = session.createQuery("select u from User u where u.user_email=?");
		q.setParameter(0,user_email);
		User user = (User)q.uniqueResult();
		tx.commit();
		session.close();
		return user;	
	}
	
}

